import React, { useEffect, useState } from "react";
import Hooks from "../../../components/hooks/Index";
import { Button, Space, Table, Tag } from "antd";
import axios from "axios";
import { Checkbox, Form, Input } from "antd";
import { Modal } from "antd";
import { addapp, addListApi } from "../../../api/user";
import { Drawer } from "antd";
function Index() {
  const [data, setData] = useState("");
  const [count, setcount] = useState(0);
  const [page, setpage] = useState(1);
  const [pageSize, setpageSize] = useState(10);
  const [keyword, setkeyword] = useState();
  const [title, setTitle] = useState("");
  const [addForm] = Form.useForm();
  const getData = () => {
    axios
      .get("/api/article/list", {
        params: {
          page: page,
          pageSize: pageSize,
          keyword,
        },
      })
      .then((res) => {
        console.log(res);
        setData(res.data.rows);
        setcount(res.data.count);
      });
  };
  useEffect(() => {
    getData();
  }, [pageSize, page, keyword]);
  //详情
  const [open, setOpen] = useState(false);
  const [qx, setqx] = useState("");
  const showDrawer = (id) => {
    setOpen(true);
    axios.get(`/article/${id}`, { params: { id } }).then((res) => {
      console.log(res);
      setqx(res.data);
    });
  };
  const onClose = () => {
    setOpen(false);
  };
  //添加
  const [isModalOpen, setIsModalOpen] = useState(false);
  const showModal = () => {
    setIsModalOpen(true);
    setTitle("添加");
    addForm.resetFields();
  };
  const handleOk = () => {
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  //添加表单
  const onFinish = async (values) => {
    console.log("Success:", values);
    if (title == "添加") {
      const data = {
        title: values.title, //文章标题
        content: values.content, //文章内容
        tagList: ["HTTP"], //标签  array[string]
        categoryList: ["HTTP"], //分类  array[string]
        authorId: 47529555, //用户id 暂时写死47529555 登陆成功后返回的用户信息
      };
      const res = await addListApi(data);
      console.log(res);
      alert("添加成功");
      setIsModalOpen(false);
      getData();
    } else if (title == "修改") {
      const data1 = {
        title: values.title, //文章标题
        content: values.content, //文章内容
        tagList: ["HTTP"], //标签  array[string]
        categoryList: ["HTTP"], //分类  array[string]
        authorId: 47529555, //用户id 暂时写死47529555 登陆成功后返回的用户信息
      };
      const res1 = await addapp(id, data1);
      console.log(res1);
      alert("编辑成功");
      setIsModalOpen(false);
      getData();
    }
  };
  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };
  //修改
  const [id, setid] = useState();
  const xiougai = (record) => {
    setIsModalOpen(true);
    setTitle("修改");
    addForm.setFieldsValue(record);
    setid(record.id);
  };

  //搜索
  const Finish = (values) => {
    console.log("Success:", values);
    setkeyword(values.keyword);
  };
  const FinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };
  //分页
  const add = (page, pageSize) => {
    setpage(page);
    setpageSize(pageSize);
  };
  const columns = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
      render: (text) => <a>{text}</a>,
    },
    {
      title: "内容",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "信息",
      dataIndex: "content",
      key: "content",
    },

    {
      title: "Action",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button onClick={() => shanchu(record.id)}>删除</Button>
          <Button type="primary" onClick={() => showDrawer(record.id)}>
            详情
          </Button>
          <Button onClick={() => xiougai(record)}>修改</Button>
        </Space>
      ),
    },
  ];
  //删除
  const shanchu = (id) => {
    setData(data.filter((data) => data.id !== id));
    alert("删除成功");
  };
  //批量删除
  const start = () => {
    const newdata = data.filter((item) => !selectedRowKeys.includes(item.id));
    setData(newdata);
    alert("批量删除成功");
  };
  //批量删除复制代码
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [loading, setLoading] = useState(false);
  const onSelectChange = (newSelectedRowKeys) => {
    console.log("selectedRowKeys changed: ", newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const hasSelected = selectedRowKeys.length > 0;

  return (
    <div>
      <Drawer
        title="详情"
        closable={{ "aria-label": "Close Button" }}
        onClose={onClose}
        open={open}
      >
        <p>{qx.title}</p>
        <p>{qx.content}</p>
      </Drawer>
      <Form
        name="basic"
        layout="inline"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 600 }}
        initialValues={{ remember: true }}
        onFinish={Finish}
        onFinishFailed={FinishFailed}
        autoComplete="off"
      >
        <Form.Item
          label="请输入搜索内容"
          name="keyword"
          rules={[{ required: true, message: "Please input your username!" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">
            搜索
          </Button>
        </Form.Item>
        <Button
          type="primary"
          onClick={start}
          disabled={!hasSelected}
          loading={loading}
        >
          批量删除
        </Button>
        <Button type="primary" onClick={showModal}>
          添加
        </Button>
      </Form>

      <Modal
        title={title}
        closable={{ "aria-label": "Custom Close Button" }}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          form={addForm}
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="内容"
            name="title"
            rules={[{ required: true, message: "Please input your username!" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="信息"
            name="content"
            rules={[{ required: true, message: "Please input your password!" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item label={null}>
            <Button type="primary" htmlType="submit">
              确定
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      <Table
        rowKey="id"
        columns={columns}
        dataSource={data}
        rowSelection={rowSelection}
        pagination={{
          total: count,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `Total ${total} items`,
          onChange: add,
        }}
      />
    </div>
  );
}

export default Hooks(Index);
